/**
 * Created by Jason on 2017/7/11.
 */

var express = require('express');
var app = express();
var http = require('http').Server(app);

var path = require('path');
app.use(express.static(path.join(__dirname, '/')));

app.engine('art', require('express-art-template'));
app.set('view options', {
    debug: process.env.NODE_ENV !== 'production'
});
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' cjatech')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

var io = require('socket.io')(http);
var redis = require('redis');
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/webIM');
var GiftModel = mongoose.model('Gift', {
    room_id: String,
    user_id: String,
    type: String,
    content: String,
    time: {type: Date, default: Date.now()}
});

/*
 *          gid: '1',
 free: 1,
 name: '爱心',
 desc: '爱心 加油',
 gprice: 10,
 price: '10元',
 img: {
 effect: 'https://i.h2.pdim.gs/39bfbcfc5a6a5dd3d6115ed8127f7c37.png',
 ext: 'https://i.h2.pdim.gs/39bfbcfc5a6a5dd3d6115ed8127f7c37.png',
 icon: 'https://i.h2.pdim.gs/39bfbcfc5a6a5dd3d6115ed8127f7c37.png',
 }
 * */
// var GiftListModel = mongoose.model('GiftList',{
//     gid:String,
//     free:Number,
//     name:String,
//     gprice:Number,
//     price:String,
//     img:{
//         effect:String,
//         ext:String,
//         icon:String
//     }
// });
//var client = redis.createClient(6379, '192.168.1.78', {});
var client = redis.createClient(6379, '127.0.0.1', {});
client.select(14);
client.on("error", function (error) {
    console.log(error);
});

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


/*
 用户数据基本结构定义
 user_id,
 nike_name,
 avatar,
 level,
 type,
 from,
 content,
 action,
 time,
 room_id,

 */
io.on('connection', function (socket) {
    // console.log(socket);
    console.log('a user connected');
    //console.log(socket);
    var room_id = socket.handshake.query.room_id;
    if (typeof (room_id) != 'undefined') {
        socket.join(room_id);
        Object.assign(socket, {room_id: room_id});
    }
    socket.on('login', function (obj) {
        socket.user_id = obj.user_id;
        Object.assign(socket, {
            user_id: obj.user_id,
            nick_name: obj.nick_name,
            avatar: obj.avatar,
            level: obj.level,
            type: obj.type,
            from: obj.from,
        });
        if (typeof (obj.room_id) != 'undefined') {
            Object.assign(socket, {
                room_id: obj.room_id
            });
            socket.join(obj.room_id);
        }

        //redis 缓存处理
        var users = null, usersCount = 0;
        if (typeof (socket.room_id) != 'undefined') {
            client.hexists(socket.room_id, obj.user_id, function (err, value) {
                if (value != 1) {
                    var user = {
                        user_id: obj.user_id,
                        nick_name: obj.nick_name,
                        avatar: obj.avatar,
                        level: obj.level,
                        type: obj.type,
                        from: obj.from,
                        time: new Date().Format('yyyy-MM-dd hh:mm:ss'),
                    };
                    client.hset(socket.room_id, obj.user_id, JSON.stringify(user));
                }
            });
        }
        Object.assign(obj, {time: new Date().Format('yyyy-MM-dd hh:mm:ss')});
        io.to(socket.room_id).emit('login', obj);
    });
    socket.on('disconnect', function () {
        console.log(socket.room_id);
        if (typeof (socket.room_id) != 'undefined') {
            client.hexists(socket.room_id, socket.user_id, function (err, value) {
                if (value == 1) {
                    client.hdel(socket.room_id, socket.user_id, redis.print);
                }

                client.hlen(socket.room_id, function (err_len, value_len) {
                    io.to(socket.room_id).emit('logout', {
                        user_id: socket.user_id,
                        level: socket.level,
                        nick_name: socket.nick_name,
                        time: new Date().Format('yyyy-MM-dd hh:mm:ss'),
                    })
                })
            })
        }
    });

    socket.on('message', function (obj) {
        if (typeof (obj.room_id) != 'undefined') {
            Object.assign(socket, {
                room_id: obj.room_id
            });
            socket.join(obj.room_id);
        }

        //如果是打赏消息则存入mongdb
        console.log(obj);
        if (obj.type == 2) {
            var gift = new GiftModel({
                room_id: socket.room_id,
                user_id: obj.user_id,
                type: obj.type,
                content: obj.content
            })
            gift.save(function (err) {
                if (err) {
                    console.log('save gift fail');
                }
            })
        }

        //当前在线人数统计
        client.hlen(socket.room_id, function (err, count) {

            count = 90+(Math.floor(Math.random()*10* count));
            //检查socket  如果服务器重启 除room_id以外的其他用户信息会丢失 这里通过obj中的user_id 从redis中取出
            if (socket.avatar == undefined || socket.avatar == null) {
                client.hget(socket.room_id, obj.user_id, function (e, value) {

                    if (value != null) {
                        var user = JSON.parse(value);
                        //给socket赋值
                        Object.assign(socket, {
                            user_id: user.user_id,
                            nick_name: user.nick_name,
                            avatar: user.avatar,
                            level: user.level,
                            type: user.type,
                            from: user.from,
                        });

                        io.to(socket.room_id).emit('message', {
                            user_id: user.user_id,
                            nick_name: user.nick_name,
                            avatar: user.avatar,
                            level: user.level,
                            type: obj.type,
                            from: user.from,
                            content: obj.content,
                            users_count: count,
                            time: new Date().Format('yyyy-MM-dd hh:mm:ss'),
                        });
                    }
                })
            } else {
                //直接从socket中获取发出
                io.to(socket.room_id).emit('message', {
                    user_id: socket.user_id,
                    nick_name: socket.nick_name,
                    avatar: socket.avatar,
                    level: socket.level,
                    type: obj.type,
                    from: socket.from,
                    content: obj.content,
                    users_count: count,
                    time: new Date().Format('yyyy-MM-dd hh:mm:ss'),
                });
            }
        });
    });
});


app.get('/', function (req, res) {
    res.render('index.art', {
        title: 'node express art-template',
        user: {
            name: 'aui',
            tags: ['art', 'template', 'nodejs']
        }
    });
})
app.get('/gifts', function (req, res) {
    res.json({name: 'jason'});
});
http.listen(8000, function () {
    console.log('listening on * 8000')
});